package com.x.gzcrm.web.controller;


import com.x.gzcrm.model.CURDResult;
import com.x.gzcrm.model.PageResult;
import com.x.gzcrm.model.User;
import com.x.gzcrm.service.IRoleService;
import com.x.gzcrm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;
    @RequestMapping(value = "/list")
    public String list(){
        return "user/list";
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public CURDResult save(User user, Integer[] roleIds){

        CURDResult result = new CURDResult();// {success:1,msg:””}
        userService.save(user,roleIds);
        return result;
    }
    @RequestMapping(value = "/add")
    public String add(Model model){
        //保存所有的角色数据
        model.addAttribute("roles",roleService.findAllRoles());
        return "user/add";
    }
    @RequestMapping(value = "/edit")
    public String edit(Model model, Integer userId){

        //通过用户id查询出用户信息，包括角色
        User user = userService.findUserAndRolesByUserId(userId);
        model.addAttribute("user",user);
        System.out.println("Edit userId:" + userId);
        //保存所有的角色数据
        model.addAttribute("roles",roleService.findAllRoles());
        return "user/edit";
    }


    @RequestMapping("listJson")
    @ResponseBody
    /**
     * page 显示的当前页
     * limit 每次显示多少条
     */
    public PageResult<User> listJson(User user, int page, int limit){
        return userService.findPageResult(user,page,limit);
    }
}
